<!DOCTYPE html>
<html>
<head>
    <title>实时日志查看器 - 优化版</title>
    <meta charset="UTF-8">
    <style>
        /* 新增过滤框样式 */
        .filter-box {
            margin: 10px 0;
            display: flex;
            gap: 10px;
        }

        .highlight {
            color: yellow;
        }

        .container {
            width: 80%;
            margin: 20px auto;
            padding: 20px;
            background-color: #f5f5f5;
            border-radius: 5px;
        }

        #logContent {
            width: 100%;
            height: 500px;
            background-color: #000;
            color: #fffefe;
            font-family: monospace;
            padding: 10px;
            overflow-y: auto;
            border: none;
            margin-top: 20px;
            white-space: pre-wrap;
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .buttons {
            display: flex;
            gap: 10px;
        }

        button {
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        button:hover {
            background-color: #45a049;
        }

        .log-line {
            margin: 0;
            padding: 0;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="header">
        <h1>实时日志查看器 - 优化版</h1>
        <div class="buttons">
            <!-- 新增清空日志按钮 -->
            <button onclick="clearLogs()">清空日志</button>
            <button onclick="toggleAutoScroll()" id="scrollButton">停止自动滚动</button>
            <button onclick="toggleConnection()" id="connectionButton">断开连接</button>
        </div>
    </div>
    <!-- 新增过滤功能 -->
    <div class="filter-box">
        <input type="text" id="keywordFilter" placeholder="输入过滤关键词">
        <button onclick="applyFilter()">过滤</button>
    </div>

    <div id="logContent"></div>
</div>

<script>
    // 配置项
    const MAX_LOG_LINES = 1000;      // 最大保留日志行数
    // 日志是否自动滚动
    let autoScroll = true;
    // websocket对象
    let ws = null;
    let currentFilter = '';

    const logContent = document.getElementById('logContent');

    // 初始化WebSocket（支持动态路径）
    function connect() {
        const filePath = prompt('请输入日志文件路径:', 'chat.log');
        if (!filePath) {
            return;
        }
        disconnect(); // 确保关闭旧连接

        const encodeFilePath = encodeURIComponent(filePath);
        const wsUrl = 'ws://localhost:8077/ws-logs?filePath=' + encodeFilePath;
        console.log("Encoded URL:", wsUrl);
        ws = new WebSocket(wsUrl);

        ws.onopen = function () {
            document.getElementById('connectionButton').textContent = '断开连接';
            console.log('WebSocket连接已建立');
        };

        ws.onmessage = function (event) {
            appendLogs([event.data]);
        };

        ws.onclose = function () {
            console.log('WebSocket连接已关闭');
            document.getElementById('connectionButton').textContent = '连接';
        };

        ws.onerror = function (error) {
            console.error('WebSocket错误:', error);
        };
    }

    function disconnect() {
        if (ws !== null) {
            ws.close();
            ws = null;
        }
    }

    function toggleConnection() {
        if (ws !== null && ws.readyState === WebSocket.OPEN) {
            disconnect();
        } else {
            connect();
        }
    }

    function toggleAutoScroll() {
        autoScroll = !autoScroll;
        document.getElementById('scrollButton').textContent =
            autoScroll ? '停止自动滚动' : '开始自动滚动';
    }

    // 改进的日志追加方法（带过滤和性能优化）
    function appendLogs(newLines) {
        newLines.forEach(line => {
            if (currentFilter && !line.includes(currentFilter)) {
                return;
            }
            const p = document.createElement('p');
            p.className = 'log-line';
            p.innerHTML = highlightKeywords(line); // 关键词高亮
            logContent.appendChild(p);
        });

        // 限制最大行数
        while (logContent.children.length > MAX_LOG_LINES) {
            logContent.removeChild(logContent.firstChild);
        }

        if (autoScroll) {
            logContent.scrollTop = logContent.scrollHeight;
        }
    }

    // 关键词高亮处理
    function highlightKeywords(text) {
        if (!currentFilter) return text;
        const regex = new RegExp(`(${currentFilter})`, 'gi');
        return text.replace(regex, '<span class="highlight">$1</span>');
    }

    // 新增过滤功能
    function applyFilter() {
        currentFilter = document.getElementById('keywordFilter').value.trim();
        logContent.innerHTML = ''; // 清空后重新渲染
    }

    // 新增清空日志功能
    function clearLogs() {
        logContent.innerHTML = '';
    }

    // 页面卸载时清理资源
    window.addEventListener('beforeunload', () => {
        disconnect();
    });

    // 页面加载时自动连接
    connect();
</script>
</body>
</html> 